<template>
  <div class="login-container">
    <div class="role-selection">
      <h3>请选择角色</h3>
      <el-button @click="selectRole('admin')">管理员</el-button>
      <el-button @click="selectRole('user')">用户</el-button>
      <el-button @click="selectRole('merchant')">商户</el-button>
    </div>
    <div class="input-login">
      <el-input v-model="form.id" placeholder="ID"></el-input>
      <el-input v-model="form.password" placeholder="password" show-password></el-input>
      <el-button type="primary" @click="login">登录</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'  // 引入 Vuex 的 useStore 函数, 用于访问 Vuex store
import { ElMessage } from 'element-plus'
import axios from '@/axios'

// 表单数据(响应式对象,任何对它的更改都会自动更新到视图中)
const form = ref({
  id: '',
  password: '',
  role: ''
})

const router = useRouter()
const store = useStore()  // 获取 Vuex store 对象

const selectRole = (role) => {
  form.value.role = role  // 更新表单数据:将 form 对象中的 role 属性设置为选中的角色
  ElMessage({  // 显示一个信息提示
    message: `已选择角色：${role}`,
    type: 'info',
  })
}

const login = async () => {
  if (!form.value.id || !form.value.password || !form.value.role) { // 检查 form 对象中的 id、password 和 role 是否都已填写
    ElMessage({
      message: '请完整填写信息',
      type: 'warning',
    })
    return
  }

  try {
    // 发起 POST 请求检查用户信息
    const response = await axios.post('/api/login', {
      id: form.value.id,
      password: form.value.password,
      role: form.value.role 
    })
    if (response.data.success) {
      ElMessage({
        message: `登录成功！角色：${form.value.role}`,
        type: 'success',
      })
      // 存储角色信息到 Vuex store
      store.dispatch('login', {
        role: form.value.role,
        data: {
          id: response.data.data.id,
          name: response.data.data.name || ''
        }
      })

      // 根据角色跳转到相应页面
      switch (form.value.role) {
        case 'admin':
          router.push('/admin')
          break
        case 'user':
          router.push('/user_home')
          break
        case 'merchant':
          router.push('/merchant')
          break
        default:
          ElMessage({
            message: '角色未识别',
            type: 'error',
          })
      }
    } else {
      ElMessage({
        message: '登录失败，请检查您的ID和密码',
        type: 'error',
      })
    }
  } catch (error) {
    ElMessage({
      message: '登录请求失败，请稍后再试',
      type: 'error',
    })
  }
}
</script>

<style scoped>
.login-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
}

.role-selection {
  display: flex;
  flex-direction: column;
  width: 300px;
  margin-bottom: 20px;
}

.input-login {
  display: flex;
  flex-direction: column;
  width: 300px;
}

.el-input {
  margin: 10px 0;
}

.el-button {
  width: 100%;
  margin-top: 10px;
}
</style>
  